from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db
import os

from html import CheckBox, DropDown, MultiSelect, RadioButton #importing the html wrappers.
import validate #import validation
import tables
import main
import datetime
import staticInits 
import cgi #for escaping html chars in forms
import re

class Course(object):
    """
    Class helps with hard coding of table for this first iteration. Will probably be removed in 
    future iterations when google data store is used.
    """
    def __init__(self, course_name, course_number):
        "Obvious constructor."
        self.course_name = course_name
        self.course_number = course_number

class Instructor(object):
    """
    Class helps with hard coding of table for this first iteration. Will probably be removed in 
    future iterations when google data store is used.
    """
    def __init__(self, firstName, lastName, eid):
        "Obvious constructor."
        self.firstName = firstName
        self.lastName = lastName
        self.eid = eid

class Section(object):
    """
    Class helps with presentation of Sections table. 
    """
    def __init__(self, name, number, instructor, numStudents, numTas):
        "Obvious constructor."
        self.name = name
        self.number = number
        self.instructor = instructor
        self.numStudents = numStudents
        self.numTas = numTas


class AddSection(webapp.RequestHandler):
    """
    This class deals with the admin add classes view.
    """

    
    def __init__(self):
        webapp.RequestHandler.__init__(self) #parent constructor call
        
        self.currentState = tables.AppState.get_by_key_name('currentState')
        self.currentSemester = self.currentState.semester
        self.currentTimeName = self.currentState.time.name   
        #DB CALLS
        ( self.instructors, self.courses, self.instructors2, self.sections1) = ( dict(), dict(), dict(), dict())
        self.sections = []
        
        #building dictionaries, keyed with name attributes which are gauranteed unique to each entry
        #building dictionaries, keyed with name attributes which are gauranteed unique to each entry
        for row in db.GqlQuery("SELECT * FROM Instructor"): self.instructors[ row.lastName + ", " + row.firstName + " - " + row.eid] = row.lastName + ", " + row.firstName + " - " + row.eid
        for row in db.GqlQuery("SELECT * FROM Instructor"): self.instructors2[ row.lastName + ", " + row.firstName + " - " + row.eid] = row
        for row in db.GqlQuery("SELECT * FROM Course"): self.courses[row.name] = row
        
        for row in db.GqlQuery("SELECT * FROM Section WHERE semester = :semester", semester=self.currentSemester): self.sections1[ row.uniqueNumber ] = row

        for s in self.sections1.values(): self.sections.append(Section(s.course.name, s.uniqueNumber, s.instructor.lastName + ", " + s.instructor.firstName, s.numStudents, s.numTas))

        self.instructor_dd = DropDown(self.instructors.values(),"","instructor_dd")
        self.course_dd = DropDown(self.courses.keys(),"","course_dd")

        
    def get(self):
        """
        Calls renderTemplate() for this class.
        """
        self.notValidated = dict()
        self.renderTemplate()

    def post(self):
        """
        Calls renderTemplate() for this class.
        """

        self.notValidated = dict()
        self.notValidated['unique'] = ""
        self.notValidated['numTas'] = ""
        self.notValidated['numStudents'] = ""
        self.notValidated['course'] = ""
        self.notValidated['instructor'] = ""

        clicked = self.request.get('submit', default_value="default")

        arguments = self.request.arguments()
        removeButton = None
        for argument in arguments:
            if re.match('remove', argument) is not None:
                removeButton = argument
                break
        if removeButton is not None:
            uniqueNumber = int(removeButton.split('remove')[1]) #getting unique to remove
            db.delete(self.sections1[uniqueNumber])
            self.sections1.pop(uniqueNumber)
            self.sections = []

            # adds this section to the db, and displays it on screen
        elif clicked == 'Add Section' :
            course = self.request.get('course_dd')
            instructor = self.request.get('instructor_dd')                                           
            unique = self.request.get('uniqueNumber')
            numStudents = self.request.get('numStudents')
            numTas = self.request.get('numTas')
            vUnique = validate.validateUniqueNumber(unique)
            vNumStudents = validate.validateNumStudents(numStudents)
            vNumTas = validate.validateNumTas(numTas)
            vCourse = validate.dropDown(course)
            vInstructor = validate.dropDown(instructor)
            uniqueUnique = validate.validateUniqueUnique(unique, self.currentSemester)
            if vUnique and vNumStudents and vNumTas and vCourse and vInstructor and uniqueUnique :
                #duplicates = [q for q in  db.GqlQuery("SELECT * FROM Section WHERE semester = :semester", semester=self.currentSemester)]
                #duplicates = [q for q in db.GqlQuery("SELECT * FROM Section WHERE unique = :u", u = unique)]
                #self.response.out.write(str(duplicates))
                instructor = str(instructor)
                cInstructor = self.instructors2[instructor]
                cCourse = self.courses[course] 
                newSection = tables.Section( course = cCourse, uniqueNumber = int(unique),  instructor = cInstructor, numTas = int(numTas), numStudents = int(numStudents), semester = self.currentSemester)
                newSection.put()
                self.sections.append(Section(course, unique, instructor, numStudents, numTas))

            else : 
                self.notValidated['unique'] = unique
                self.notValidated['numStudents'] = numStudents
                self.notValidated['numTas'] = numTas
                self.notValidated['course'] = DropDown(options = self.course_dd.options, selected = course, name = 'course_dd')
                self.notValidated['instructor'] =  DropDown(options = self.instructor_dd.options, selected = instructor, name = 'instructor_dd')
                if not vUnique : 
                    self.response.out.write('<br><font color="red">Please enter a valid unique number.</font><br />')
                if not vNumStudents : 
                    self.response.out.write('<br><font color="red">Please enter a valid number of students.</font><br />')
                if not vNumTas : 
                    self.response.out.write('<br><font color="red">Please enter a valid number of TAs.</font><br />')
                if not vCourse : 
                    self.response.out.write('<br><font color="red">Please select a course name.</font><br />')
                if not vInstructor : 
                    self.response.out.write('<br><font color="red">Please select an instructor.</font><br />')
                if not uniqueUnique : 
                    self.response.out.write('<br><font color="red">The unique number you have specified is already used this semester.</font><br />')

            
        self.__init__()
        self.renderTemplate()
    
    def renderTemplate(self, addValid = "") :
        """
        Renders the Template setup.html for this class.
        """

        self.sections.sort(key = lambda x : x.name.lower() )

        #setting up template dictionary
        templateValues = {
            #'table' : table
            'instructors': self.instructor_dd,
            'courses': self.course_dd,
            'sections' : self.sections, 
            'badUnique' : self.notValidated['unique'] if 'unique' in self.notValidated else "",
            'badCourse' : self.course_dd  if 'course' not in self.notValidated or self.notValidated['course'] == "" else self.notValidated['course'],
            'badNumTas' : self.notValidated['numTas'] if 'numTas' in self.notValidated else "",
            'badNumStudents' : self.notValidated['numStudents'] if 'numStudents' in self.notValidated else "",
            'badInstructor' : self.instructor_dd  if 'instructor' not in self.notValidated or self.notValidated['instructor'] == "" else self.notValidated['instructor'],
            'currentSemester': self.currentSemester,
            }


        #telling it to use the template
        path = os.path.join(os.path.dirname(__file__), 'addSection.html')
        self.response.out.write(template.render(path, templateValues))



application = webapp.WSGIApplication([('/admin/addSection', AddSection)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

